/*
 * @Description:
 * @Version: 2.0
 * @Autor: zouxuemiao
 * @Date: 2022-03-24 15:48:35
 * @LastEditors: zouxuemiao
 * @LastEditTime: 2022-03-28 19:37:41
 */
var mockjs = require('mockjs');
var _ = require('lodash');
var express = require('express');
var router = express.Router();
// 假数据
let sourceData = [
    {
        id: 0,
        content: '做作业',
        state: 0, // 完成状态： 0 未完成， 1 已完成
    },
    {
        id: 1,
        content: '干饭',
        state: 0,
    },
    {
        id: 2,
        content: '睡觉',
        state: 1,
    },
];
let newSourceData = _.cloneDeep(sourceData);
// 筛选 ---> 0:全部，1 所有未完成， 2 所有已完成
const filterByState = (finishState) => {
    let searchResult;
    switch (finishState) {
        case 'all':
            searchResult = newSourceData;
            break;
        case 'unfinished':
            searchResult = newSourceData.filter((item) => {
                return item.state == 0;
            });
            break;
        case 'finished':
            searchResult = newSourceData.filter((item) => {
                return item.state == 1;
            });
            break;
        default:
            break;
    }
    return searchResult;
};
// 获取list  
router.get('/getList', (req, res) => {
    const filterResult = filterByState(req.query.finishState);
    res.json({
        data: filterResult,
        msg: 'ok'
    });
});
// 新增 list
router.post('/add', (req, res) => {
    // post -- req.body  , get -- query
    newSourceData.unshift({
        id: Date.now(),
        content: req.body.content,
        state: 0,
    });
    // 返回
    res.json({
        data: newSourceData,
        msg: '新增成功'
    });
});
// 编辑文本
router.post('/edit', (req, res) => {
    newSourceData = newSourceData.map((item) => {
      if(item.id == req.body.id) {
        item.content = req.body.newContent
      }
      return item
    })
    // 返回
    res.json({
      data: newSourceData,
      msg: '编辑成功'
    })
});
// 删除
router.post('/del', (req, res) => {
    const filterResult = filterByState(req.body.nowState);
    sourceData = filterResult && filterResult.filter((item) => {
        return item.id !== req.body.id;
    });
    newSourceData = newSourceData.filter(item => {
        return item.id !== req.body.id;
    });
    // 返回
    res.json({
        data: sourceData,
        msg: '删除成功'
    });
});
// 修改 list 完成状态 -- checkbox
router.post('/change', (req, res) => {
    console.log('接收到修改', req.body);
    newSourceData = newSourceData.map((item) => {
        if (item.id == req.body.id) {
            item.state = item.state == 1 ? 0 : 1;
        }
        return item;
    });
    const filterResult = filterByState(req.body.nowState);
    // 返回
    res.json({
        data: filterResult,
        msg: '修改成功'
    });
});
module.exports = router;
